package com.vma.jifu.orderList.service.impl;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.sun.org.apache.xpath.internal.operations.Or;
import com.vma.jifu.bizModel.model.*;
import com.vma.jifu.orderList.service.OrderService;
import com.vma.tools.AppException;
import com.vma.tools.StringUtils;
import com.vma.tools.Utils;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by chenzui on 2017/6/16.
 */
public class OrderServiceImpl implements OrderService {


    public Map commit(Integer userId,Integer addressId, Integer offerId, Integer offer_num, String remark, Integer offerPrice) {
        Map result = new HashMap();
        Date date = new Date();
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmm");
        Random random = new Random();
        String dateStr =  df.format(date).toString();
        String nbr= dateStr+random.nextInt(100);
        Offer offer = Offer.dao.findFirst("select * from offer where id = ? and status = 1",offerId);
        if(offer == null){
            throw new AppException("-1","商品失效或商品非法");
        }
        OrderList orderList = new OrderList().setUserId(userId).setCreateTime(date)
                .setAddressId(addressId).setOfferNum(offer_num).setOfferId(offerId)
                .setOfferPrice(offerPrice).setRemark(remark).setOfferVersion(offer.getVersion())
                .setOrderNbr(nbr).setTotalFee(offerPrice*offer_num).setStatus(1);

        Address address = Address.dao.findById(orderList.getAddressId());
        Areas areas = Areas.dao.findFirst("select * from areas where area = ?",address.getArea());
        if(areas == null){
            throw new AppException("-1","地区数据错误，请联系管理员");
        }
        orderList.setAreaId(areas.getAreaid());

        orderList.save();
        result.put("orderNbr",nbr);
        result.put("orderFee",orderList.getTotalFee());

//=============================================支付未对接生成数据=====================================================
//        User user = User.dao.findById(orderList.getUserId());
//        int buyFlag = user.getDiscountFlag();
//
//        User first = User.dao.findById(user.getFirstParentUserId());
//        User second = User.dao.findById(user.getSecondParentUserId());
//        User third = User.dao.findById(user.getThirdParentUserId());
////        1提成2津贴3推广奖励4区域代理提成5推荐合伙人奖励
//        if(buyFlag == 0){
//            //首次购物
//            if(first != null){
//
//                new TgAward().setStatus(0).setUserId(first.getId()).setOrderId(orderList.getId())
//                        .setCreateTime(date).setUpdateTime(date).setFee(orderList.getTotalFee()/10)
//                        .setType(1).save();
//                if(second != null){
//
//
//                    new TgAward().setStatus(0).setUserId(second.getId()).setOrderId(orderList.getId())
//                            .setCreateTime(date).setUpdateTime(date).setFee(orderList.getTotalFee()/10)
//                            .setType(2).save();
//                    if(third != null){
//
//                        new TgAward().setStatus(0).setUserId(third.getId()).setOrderId(orderList.getId())
//                                .setCreateTime(date).setUpdateTime(date).setFee(orderList.getTotalFee()/10)
//                                .setType(2).save();
//                    }
//                }
//            }
//
//        }else {
//            new TgAward().setStatus(0).setUserId(userId).setOrderId(orderList.getId())
//                    .setCreateTime(date).setUpdateTime(date).setFee(orderList.getTotalFee()/20)
//                    .setType(1).save();
//            //复购
//            if(first != null){
//                new TgAward().setStatus(0).setUserId(first.getId()).setOrderId(orderList.getId())
//                        .setCreateTime(date).setUpdateTime(date).setFee(orderList.getTotalFee()/100/3)
//                        .setType(2).save();
//
//                if(second != null){
//                    new TgAward().setStatus(0).setUserId(second.getId()).setOrderId(orderList.getId())
//                            .setCreateTime(date).setUpdateTime(date).setFee(orderList.getTotalFee()/100/3)
//                            .setType(2).save();
//                    if(third != null){
//                        new TgAward().setStatus(0).setUserId(third.getId()).setOrderId(orderList.getId())
//                                .setCreateTime(date).setUpdateTime(date).setFee(orderList.getTotalFee()/100/3)
//                                .setType(2).save();
//                    }
//                }
//            }
//        }
//        Integer areaId = orderList.getAreaId();
//        JoinFee joinFee = JoinFee.dao.findFirst("SELECT * FROM join_fee WHERE area = ?",areaId);
//        if(joinFee != null && joinFee.getStatus().equals(0)){
//            new TgAward().setStatus(0).setUserId(joinFee.getUserId()).setOrderId(orderList.getId())
//                    .setCreateTime(date).setUpdateTime(date).setFee(orderList.getTotalFee()/10)
//                    .setType(4).save();
//        }
//===========================================支付为对接生成数据=======================================================

        return result;
    }

    public Page<OrderList> qryOrderListByPage(Integer userId, Integer cPage, Integer pSize, Integer status) {
        String condition = "";
        List param = new ArrayList();
        param.add(userId);
        if(status == 999){
            condition += "and status != -1 ";
        }else {
            condition += "and status = ?";
            param.add(status);
        }
        Page<OrderList> orderListPage = OrderList.dao.paginate(cPage,pSize,
                "SELECT *",
                "FROM order_list WHERE  user_id=? "+condition+" order by create_time desc",
                param.toArray());
        if(orderListPage.getList() != null && orderListPage.getList().size() != 0){
            Offer offer = null;
            for(OrderList ol : orderListPage.getList()){
                offer = Offer.dao.findById(ol.getOfferId(),ol.getOfferVersion());
                ol.put("offer_name",offer.getOfferName());
                ol.put("offer_img_url",offer.getImgUrl());
            }
        }

        return orderListPage;
    }

    public Page<OrderList> qryFistOrderListByPage(Integer userId, Integer cPage, Integer pSize, Integer status) {
        Page<OrderList> orderListPage = OrderList.dao.paginate(cPage,pSize,
                "SELECT ol.*,o.offer_name,u.login_account,o.img_url offer_img_url",
                "FROM order_list ol,tg_award rc,offer o,user u\n" +
                        "WHERE ol.id = rc.order_id\n" +
                        "AND ol.offer_id = o.id\n" +
                        "AND ol.user_id = u.id\n" +
                        "AND u.first_parent_user_id = ?\n" +
                        "AND rc.status = ? AND ol.status != -1 AND rc.user_id = ?",userId,status,userId);
        return orderListPage;
    }

    public Page<OrderList> qrySecondOrderListByPage(Integer userId, Integer cPage, Integer pSize, Integer status) {
        Page<OrderList> orderListPage = OrderList.dao.paginate(cPage,pSize,
                "SELECT ol.*,o.offer_name,u.login_account,o.img_url offer_img_url",
                "FROM order_list ol,tg_award rc,offer o,user u\n" +
                        "WHERE ol.id = rc.order_id\n" +
                        "AND ol.offer_id = o.id\n" +
                        "AND ol.user_id = u.id\n" +
                        "AND u.second_parent_user_id = ?\n" +
                        "AND rc.status = ?",userId,status);
        return orderListPage;
    }

    public Page<OrderList> qryThirdOrderListByPage(Integer userId, Integer cPage, Integer pSize, Integer status) {
        Page<OrderList> orderListPage = OrderList.dao.paginate(cPage,pSize,
                "SELECT ol.*,o.offer_name,u.login_account,o.img_url offer_img_url",
                "FROM order_list ol,tg_award rc,offer o,user u\n" +
                        "WHERE ol.id = rc.order_id\n" +
                        "AND ol.offer_id = o.id\n" +
                        "AND ol.user_id = u.id\n" +
                        "AND u.third_parent_user_id = ?\n" +
                        "AND rc.status = ?",userId,status);
        return orderListPage;
    }

    public Page<OrderList> qryJTOrderListByPage(Integer userId, Integer cPage, Integer pSize, Integer status) {
        Page<OrderList> orderListPage = OrderList.dao.paginate(cPage,pSize,
                "SELECT ol.*,o.offer_name,u.login_account,o.img_url offer_img_url",
                "FROM order_list ol,tg_award rc,offer o,user u\n" +
                        "WHERE ol.id = rc.order_id\n" +
                        "AND ol.offer_id = o.id\n" +
                        "AND ol.user_id = u.id AND rc.user_id = ? AND rc.type in (2)\n" +
                        "AND (u.third_parent_user_id = ? OR u.second_parent_user_id = ?)\n" +
                        "AND rc.status = ? AND ol.status != -1",userId,userId,userId,status);
        return orderListPage;
    }

    public Page<Record> qryOrderList(Integer cPage, Integer pSize, String status, String ordernbr, String province, String city, String area, String start, String end,String offer_name){

        String condition = "";
        List param = new ArrayList();
        if(status == null || "".equals(status)){

        }else {
            condition += "and t.status = ?";
            param.add(status);
        }
        if(ordernbr == null || "".equals(ordernbr)){

        }else {
            condition += "and t.order_nbr like ? ";
            param.add("%"+ordernbr+"%");
        }
        if(province != null &&  !"".equals(province)){

            condition += "and ad.province = ?";
            param.add(province);
        }
        if(city != null &&  !"".equals(city)){

            condition += "and ad.city = ?";
            param.add(city);
        }
        if(area != null &&  !"".equals(area)){

            condition += "and ad.area = ?";
            param.add(area);
        }
        if(start != null && !"".equals(start)){
            condition += "and t.create_time > ? ";
            param.add(start);
        }
        if(end != null && !"".equals(end)){
            condition += "and t.create_time < ? ";
            param.add(end);
        }
        if(offer_name != null && !"".equals(offer_name)){
            condition += "and of.offer_name like ? ";
            param.add('%'+offer_name+'%');
        }

        Page<Record> orderListPage = Db.paginate(cPage,pSize,
                "SELECT t.*,u.nick_name,u.phone,of.offer_name",
                "FROM order_list t left join offer of on of.id=t.offer_id and of.version= t.offer_version " +
                        "left join address ad on t.address_id= ad.id left join user u on u.id=t.user_id" +
                        " WHERE   1=1  "+condition + " order by t.id desc ",
                param.toArray());

        return orderListPage;

    }

    public void updateOrder(Integer userId, Integer orderId, Integer status) {
        // 1待支付2待发货3待收货4待评价5已完成0已取消6退款中7已退款-1已删除
        OrderList orderList = OrderList.dao.findById(orderId);
        User user = User.dao.findById(orderList.getUserId());
        User first = User.dao.findById(user.getFirstParentUserId());
        User second = User.dao.findById(user.getSecondParentUserId());
        User third = User.dao.findById(user.getThirdParentUserId());
        if(status == 0){
            if(orderList.getStatus() != 1){
                throw new AppException("-1","订单状态不可取消");
            }else {
                orderList.setStatus(status).update();
                if(first != null) {
                    TgAward firstAward = TgAward.dao.findFirst("SELECT * FROM tg_award WHERE order_id = ? AND user_id = ?", orderId, first.getId());
                    if(firstAward != null){
                        firstAward.setStatus(-1).update();
                        if(second != null){
                            TgAward secondAward = TgAward.dao.findFirst("SELECT * FROM tg_award WHERE order_id = ? AND user_id = ?", orderId, second.getId());
                            secondAward.setStatus(-1).update();
                            if(third != null){
                                TgAward thirdAward = TgAward.dao.findFirst("SELECT * FROM tg_award WHERE order_id = ? AND user_id = ?", orderId, third.getId());
                                thirdAward.setStatus(-1).update();

                            }
                        }
                    }
                }

                String areaId = orderList.getAreaId();
                JoinFee joinFee = JoinFee.dao.findFirst("SELECT * FROM join_fee WHERE area = ?",areaId);
                if(joinFee != null && joinFee.getStatus().equals(1)){
                    TgAward areaAward = TgAward.dao.findFirst("SELECT * FROM tg_award WHERE order_id = ? AND user_id = ?", orderId, joinFee.getUserId());
                    if(areaAward != null){
                        areaAward.setStatus(-1).update();
                    }
                }
            }
        }else if(status == 6){
            if(orderList.getStatus() != 3){
                throw new AppException("-1","订单状态不可申请退款");
            }else {
                orderList.setStatus(status).update();
            }
        }else if(status == -1){
            if(orderList.getStatus() != 0){
                throw new AppException("-1","订单状态不可删除");
            }else {
                orderList.setStatus(status).update();
            }
        }else if(status == 4){
            orderList.setStatus(status).update();
            if(first != null) {
                TgAward firstAward = TgAward.dao.findFirst("SELECT * FROM tg_award WHERE order_id = ? AND user_id = ?", orderId, first.getId());
                firstAward.setStatus(1).update();
                if(second != null){
                    TgAward secondAward = TgAward.dao.findFirst("SELECT * FROM tg_award WHERE order_id = ? AND user_id = ?", orderId, second.getId());
                    secondAward.setStatus(1).update();
                    if(third != null){
                        TgAward thirdAward = TgAward.dao.findFirst("SELECT * FROM tg_award WHERE order_id = ? AND user_id = ?", orderId, third.getId());
                        thirdAward.setStatus(1).update();

                    }
                }
            }

            String areaId = orderList.getAreaId();
            JoinFee joinFee = JoinFee.dao.findFirst("SELECT * FROM join_fee WHERE area = ?",areaId);
            if(joinFee != null && joinFee.getStatus().equals(1)){
                TgAward areaAward = TgAward.dao.findFirst("SELECT * FROM tg_award WHERE order_id = ? AND user_id = ?", orderId, joinFee.getUserId());
                if(areaAward != null){
                    areaAward.setStatus(1).update();
                }
            }
            if(user.getDiscountFlag() == 0){
                user.setDiscountFlag(1).update();//复购
            }


        }else if(status == 5){
            Date date = new Date();
            StringBuffer sb = new StringBuffer("您");
            if(!StringUtils.isEmpty(user.getNickName())){
                sb.append("【"+user.getNickName()+"】");
            }
            sb.append("的订单"+orderList.getOrderNbr()).append("确认收货成功\n");
            sb.append("订单号:"+orderList.getOrderNbr()).append("\n");
            sb.append("确认时间:"+ Utils.formatDate(date,"yyyy-MM-dd HH:mm:ss")+"\n");
            sb.append("确认金额:"+ BigDecimal.valueOf(Long.valueOf(orderList.getTotalFee())).divide(new BigDecimal(100)).toString()+"元\n");

            SystemMessage message = new SystemMessage().setTitle("支付成功").setContent(sb.toString()).setType(2).setStatus(1).setIsDelete(0).setCreateTime(date);
            message.save();
            Message2User message2User = new Message2User().setMessageId(message.getId()).setIsDelete("0").setStatus("0").setUserId(user.getId()).setCreateTime(date)
                    .setVersion(date);
            message2User.save();
        }else {
            throw new AppException("-2","请求参数非法");
        }
    }

    public OrderList getOrderDetail(Integer userId, Integer orderId) {
        OrderList orderList = OrderList.dao.findById(orderId);
        Address address = Address.dao.findById(orderList.getAddressId());
        orderList.put("address",address);

        Offer offer = Offer.dao.findById(orderList.getOfferId(),orderList.getOfferVersion());
        orderList.put("offer",offer);
        return orderList;
    }

    public boolean callBackForOrder(String orderNbr,Integer payType) {
        Date date = new Date();
        OrderList orderList = OrderList.dao.findFirst("SELECT * FROM order_list WHERE order_nbr = ?",orderNbr);
        if(orderList == null) return false;
        orderList.setPayType(payType).setStatus(2).update();
        //查询用户是否复购
        User user = User.dao.findById(orderList.getUserId());
        int buyFlag = user.getDiscountFlag();

        User first = User.dao.findById(user.getFirstParentUserId());
        User second = User.dao.findById(user.getSecondParentUserId());
        User third = User.dao.findById(user.getThirdParentUserId());
//        1提成2津贴3推广奖励4区域代理提成5推荐合伙人奖励
        if(buyFlag == 0){
            //首次购物
            if(first != null){

                new TgAward().setStatus(0).setUserId(first.getId()).setOrderId(orderList.getId())
                        .setCreateTime(date).setUpdateTime(date).setFee(orderList.getTotalFee()/10)
                        .setType(1).save();

                StringBuffer sb = new StringBuffer("会员");
                if(!StringUtils.isEmpty(user.getNickName())){
                    sb.append("【"+user.getNickName()+"】");
                }else {
                    sb.append("【"+user.getLoginAccount()+"】");
                }
                sb.append("的订单"+orderNbr).append("支付成功，您将获得提成或者津贴"+
                        BigDecimal.valueOf(Long.valueOf(orderList.getTotalFee()/10)).divide(new BigDecimal(100)).toString()+"元");
                sb.append("订单号:"+orderNbr).append("\n");
                sb.append("支付时间:"+ Utils.formatDate(date,"yyyy-MM-dd HH:mm:ss")+"\n");
                sb.append("支付金额:"+ BigDecimal.valueOf(Long.valueOf(orderList.getTotalFee())).divide(new BigDecimal(100)).toString()+"元\n");
                if(payType == 1){
                    sb.append("支付方式:微信钱包");
                }else {
                    sb.append("支付方式:支付宝");
                }
                SystemMessage message = new SystemMessage().setTitle("我的会员付款成功").setContent(sb.toString()).setType(2).setStatus(1).setIsDelete(0).setCreateTime(date);
                message.save();
                Message2User message2User = new Message2User().setMessageId(message.getId()).setIsDelete("0").setStatus("0").setUserId(user.getId()).setCreateTime(date)
                        .setVersion(date);
                message2User.save();

                if(second != null){


                    new TgAward().setStatus(0).setUserId(second.getId()).setOrderId(orderList.getId())
                            .setCreateTime(date).setUpdateTime(date).setFee(orderList.getTotalFee()/10)
                            .setType(2).save();
                    sb = new StringBuffer("会员");
                    if(!StringUtils.isEmpty(user.getNickName())){
                        sb.append("【"+user.getNickName()+"】");
                    }else {
                        sb.append("【"+user.getLoginAccount()+"】");
                    }
                    sb.append("的订单"+orderNbr).append("支付成功，您将获得提成或者津贴"+
                            BigDecimal.valueOf(Long.valueOf(orderList.getTotalFee()/10)).divide(new BigDecimal(100)).toString()+"元");
                    sb.append("订单号:"+orderNbr).append("\n");
                    sb.append("支付时间:"+ Utils.formatDate(date,"yyyy-MM-dd HH:mm:ss")+"\n");
                    sb.append("支付金额:"+ BigDecimal.valueOf(Long.valueOf(orderList.getTotalFee())).divide(new BigDecimal(100)).toString()+"元\n");
                    if(payType == 1){
                        sb.append("支付方式:微信钱包");
                    }else {
                        sb.append("支付方式:支付宝");
                    }
                    message = new SystemMessage().setTitle("我的会员付款成功").setContent(sb.toString()).setType(2).setStatus(1).setIsDelete(0).setCreateTime(date);
                    message.save();
                    message2User = new Message2User().setMessageId(message.getId()).setIsDelete("0").setStatus("0").setUserId(user.getId()).setCreateTime(date)
                            .setVersion(date);
                    message2User.save();
                    if(third != null){

                        new TgAward().setStatus(0).setUserId(third.getId()).setOrderId(orderList.getId())
                                .setCreateTime(date).setUpdateTime(date).setFee(orderList.getTotalFee()/10)
                                .setType(2).save();
                        sb = new StringBuffer("会员");
                        if(!StringUtils.isEmpty(user.getNickName())){
                            sb.append("【"+user.getNickName()+"】");
                        }else {
                            sb.append("【"+user.getLoginAccount()+"】");
                        }
                        sb.append("的订单"+orderNbr).append("支付成功，您将获得提成或者津贴"+
                                BigDecimal.valueOf(Long.valueOf(orderList.getTotalFee()/10)).divide(new BigDecimal(100)).toString()+"元");
                        sb.append("订单号:"+orderNbr).append("\n");
                        sb.append("支付时间:"+ Utils.formatDate(date,"yyyy-MM-dd HH:mm:ss")+"\n");
                        sb.append("支付金额:"+ BigDecimal.valueOf(Long.valueOf(orderList.getTotalFee())).divide(new BigDecimal(100)).toString()+"元\n");
                        if(payType == 1){
                            sb.append("支付方式:微信钱包");
                        }else {
                            sb.append("支付方式:支付宝");
                        }
                        message = new SystemMessage().setTitle("我的会员付款成功").setContent(sb.toString()).setType(2).setStatus(1).setIsDelete(0).setCreateTime(date);
                        message.save();
                        message2User = new Message2User().setMessageId(message.getId()).setIsDelete("0").setStatus("0").setUserId(user.getId()).setCreateTime(date)
                                .setVersion(date);
                        message2User.save();
                    }
                }
            }

        }else {
            StringBuffer sb = new StringBuffer();
            SystemMessage message = null;
            Message2User message2User = null;
            new TgAward().setStatus(0).setUserId(user.getId()).setOrderId(orderList.getId())
                    .setCreateTime(date).setUpdateTime(date).setFee(orderList.getTotalFee()/20)
                    .setType(1).save();
            //复购
            if(first != null){
                new TgAward().setStatus(0).setUserId(first.getId()).setOrderId(orderList.getId())
                        .setCreateTime(date).setUpdateTime(date).setFee(orderList.getTotalFee()/100/3)
                        .setType(2).save();
                sb = new StringBuffer("会员");
                if(!StringUtils.isEmpty(user.getNickName())){
                    sb.append("【"+user.getNickName()+"】");
                }else {
                    sb.append("【"+user.getLoginAccount()+"】");
                }
                sb.append("的订单"+orderNbr).append("支付成功，您将获得提成或者津贴"+
                        BigDecimal.valueOf(Long.valueOf(orderList.getTotalFee()/10)).divide(new BigDecimal(100)).toString()+"元");
                sb.append("订单号:"+orderNbr).append("\n");
                sb.append("支付时间:"+ Utils.formatDate(date,"yyyy-MM-dd HH:mm:ss")+"\n");
                sb.append("支付金额:"+ BigDecimal.valueOf(Long.valueOf(orderList.getTotalFee())).divide(new BigDecimal(100)).toString()+"元\n");
                if(payType == 1){
                    sb.append("支付方式:微信钱包");
                }else {
                    sb.append("支付方式:支付宝");
                }
                message = new SystemMessage().setTitle("我的会员付款成功").setContent(sb.toString()).setType(2).setStatus(1).setIsDelete(0).setCreateTime(date);
                message.save();
                message2User = new Message2User().setMessageId(message.getId()).setIsDelete("0").setStatus("0").setUserId(user.getId()).setCreateTime(date)
                        .setVersion(date);
                message2User.save();

                if(second != null){
                    new TgAward().setStatus(0).setUserId(second.getId()).setOrderId(orderList.getId())
                            .setCreateTime(date).setUpdateTime(date).setFee(orderList.getTotalFee()/100/3)
                            .setType(2).save();
                    sb = new StringBuffer("会员");
                    if(!StringUtils.isEmpty(user.getNickName())){
                        sb.append("【"+user.getNickName()+"】");
                    }else {
                        sb.append("【"+user.getLoginAccount()+"】");
                    }
                    sb.append("的订单"+orderNbr).append("支付成功，您将获得提成或者津贴"+
                            BigDecimal.valueOf(Long.valueOf(orderList.getTotalFee()/10)).divide(new BigDecimal(100)).toString()+"元");
                    sb.append("订单号:"+orderNbr).append("\n");
                    sb.append("支付时间:"+ Utils.formatDate(date,"yyyy-MM-dd HH:mm:ss")+"\n");
                    sb.append("支付金额:"+ BigDecimal.valueOf(Long.valueOf(orderList.getTotalFee())).divide(new BigDecimal(100)).toString()+"元\n");
                    if(payType == 1){
                        sb.append("支付方式:微信钱包");
                    }else {
                        sb.append("支付方式:支付宝");
                    }
                    message = new SystemMessage().setTitle("我的会员付款成功").setContent(sb.toString()).setType(2).setStatus(1).setIsDelete(0).setCreateTime(date);
                    message.save();
                    message2User = new Message2User().setMessageId(message.getId()).setIsDelete("0").setStatus("0").setUserId(user.getId()).setCreateTime(date)
                            .setVersion(date);
                    message2User.save();
                    if(third != null){
                        new TgAward().setStatus(0).setUserId(third.getId()).setOrderId(orderList.getId())
                                .setCreateTime(date).setUpdateTime(date).setFee(orderList.getTotalFee()/100/3)
                                .setType(2).save();
                    }
                    sb = new StringBuffer("会员");
                    if(!StringUtils.isEmpty(user.getNickName())){
                        sb.append("【"+user.getNickName()+"】");
                    }else {
                        sb.append("【"+user.getLoginAccount()+"】");
                    }
                    sb.append("的订单"+orderNbr).append("支付成功，您将获得提成或者津贴"+
                            BigDecimal.valueOf(Long.valueOf(orderList.getTotalFee()/10)).divide(new BigDecimal(100)).toString()+"元");
                    sb.append("订单号:"+orderNbr).append("\n");
                    sb.append("支付时间:"+ Utils.formatDate(date,"yyyy-MM-dd HH:mm:ss")+"\n");
                    sb.append("支付金额:"+ BigDecimal.valueOf(Long.valueOf(orderList.getTotalFee())).divide(new BigDecimal(100)).toString()+"元\n");
                    if(payType == 1){
                        sb.append("支付方式:微信钱包");
                    }else {
                        sb.append("支付方式:支付宝");
                    }
                    message = new SystemMessage().setTitle("我的会员付款成功").setContent(sb.toString()).setType(2).setStatus(1).setIsDelete(0).setCreateTime(date);
                    message.save();
                    message2User = new Message2User().setMessageId(message.getId()).setIsDelete("0").setStatus("0").setUserId(user.getId()).setCreateTime(date)
                            .setVersion(date);
                    message2User.save();
                }
            }
        }

        String areaId = orderList.getAreaId();
        JoinFee joinFee = JoinFee.dao.findFirst("SELECT * FROM join_fee WHERE area = ?",areaId);
        if(joinFee != null && joinFee.getStatus().equals(1)){
            new TgAward().setStatus(0).setUserId(joinFee.getUserId()).setOrderId(orderList.getId())
                    .setCreateTime(date).setUpdateTime(date).setFee(orderList.getTotalFee()/10)
                    .setType(4).save();
        }
//        您【水木清华】的订单2017051119463742支付成功。
//        订单号：2017051119463742
//        支付时间：2017-05-11 14:19:01
//        支付金额：99元
//        支付方式：微信钱包
        StringBuffer sb = new StringBuffer("您");
        if(!StringUtils.isEmpty(user.getNickName())){
            sb.append("【"+user.getNickName()+"】");
        }
        sb.append("的订单"+orderNbr).append("支付成功\n");
        sb.append("订单号:"+orderNbr).append("\n");
        sb.append("支付时间:"+ Utils.formatDate(date,"yyyy-MM-dd HH:mm:ss")+"\n");
        sb.append("支付金额:"+ BigDecimal.valueOf(Long.valueOf(orderList.getTotalFee())).divide(new BigDecimal(100)).toString()+"元\n");
        if(payType == 1){
            sb.append("支付方式:微信钱包");
        }else {
            sb.append("支付方式:支付宝");
        }
        SystemMessage message = new SystemMessage().setTitle("支付成功").setContent(sb.toString()).setType(2).setStatus(1).setIsDelete(0).setCreateTime(date);
        message.save();
        Message2User message2User = new Message2User().setMessageId(message.getId()).setIsDelete("0").setStatus("0").setUserId(user.getId()).setCreateTime(date)
                .setVersion(date);
        message2User.save();
        return true;
    }

    public Page<OrderList> qryMyAgentOrders(Integer userId,Integer agentId, Integer cPage, Integer pSize, String start, String end) {
        String condition = "";
        List param = new ArrayList();
        param.add(agentId);
        param.add(userId);
        if(!StringUtils.isEmpty(start)){
            condition += " and create_time >= ?";
            param.add(start);
        }
        if(!StringUtils.isEmpty(end)){
            condition += " and create_time <= ?";
            param.add(end);
        }
        Page<OrderList> orderListPage = OrderList.dao.paginate(cPage,pSize,
                "SELECT ol.*,o.offer_name,u.login_account,o.img_url offer_img_url,rc.fee award",
                "FROM order_list ol,tg_award rc,offer o,user u\n" +
                        "WHERE ol.id = rc.order_id\n" +
                        "AND ol.offer_id = o.id\n" +
                        "AND ol.user_id = u.id\n" +
                        "AND ol.user_id = ?\n" +
                        "AND rc.status != -1\n" +
                        "AND rc.user_id = u.first_parent_user_id\n" +
                        "AND u.first_parent_user_id = ? \n" +
                        "AND ol.status not in (-1,0)"+condition,param.toArray());
        return orderListPage;
    }

    public Map qryOrderCnt(Integer userId) {
        // 1待支付2待发货3待收货4待评价5已完成0已取消6退款中7已退款999查全部

        Record status1 = Db.findFirst("SELECT count(1) cnt FROM order_list WHERE status = 1 and user_id = ?",userId);
        Record status2 = Db.findFirst("SELECT count(1) cnt FROM order_list WHERE status = 2 and user_id = ?",userId);
        Record status3 = Db.findFirst("SELECT count(1) cnt FROM order_list WHERE status = 3 and user_id = ?",userId);
        Record status4 = Db.findFirst("SELECT count(1) cnt FROM order_list WHERE status = 4 and user_id = ?",userId);

        Map result = new HashMap();
        result.put("1",status1.getLong("cnt"));
        result.put("2",status2.getLong("cnt"));
        result.put("3",status3.getLong("cnt"));
        result.put("4",status4.getLong("cnt"));

        return result;
    }

    public Page<OrderList> qryAreaOrder(Integer areaId,Integer type, Integer cPage, Integer pSize) {
        String condition = "";
        if(type == 0){
            condition += "and ta.status in (0) ";
        }else {
            condition += "and ta.status in (1)";
        }
        Page<OrderList> orderListPage = OrderList.dao.paginate(cPage,pSize,
                "SELECT ol.*",
                "FROM order_list ol,tg_award ta WHERE ol.status not in (0,-1) and ol.id = ta.order_id AND ta.type = 4 and ol.area_id = ? "+condition+" order by ol.create_time desc",
                areaId);
        if(orderListPage.getList() != null && orderListPage.getList().size() != 0){
            Offer offer = null;
            for(OrderList ol : orderListPage.getList()){
                offer = Offer.dao.findById(ol.getOfferId(),ol.getOfferVersion());
                ol.put("offer_name",offer.getOfferName());
                ol.put("offer_img_url",offer.getImgUrl());
            }
        }

        return orderListPage;
    }
}
